package com.shiguiwu.springboot3.service;

import com.shiguiwu.springboot3.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class TokenBlackService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtils jwtUtils;

    public void addToBlacklist(String token) {

        Date expiration = jwtUtils.extractExpiration(token);
        long ttl = expiration.getTime() - System.currentTimeMillis();

        // 如果Token还有效，则加入Redis，并设置其TTL
        if (ttl > 0) {
            String tokenId = jwtUtils.extractClaim(token, Claims::getId); // 或使用 jti claim
            redisTemplate.opsForValue().set("blacklist:" + tokenId, "logged_out", ttl, TimeUnit.MILLISECONDS);
        }
    }

    public boolean isBlacklisted(String tokenId) {
        return Boolean.TRUE.equals(redisTemplate.hasKey("blacklist:" + tokenId));
    }
}